import { cloneDeep, assign, head, isArray, last, slice, round, isEqual, filter } from 'lodash'
import { Message } from 'view-design'
import dayjs from 'dayjs'
import {
  fetchTableData,
  fetchTreeMap,
  fetchCenterTopCandData,
  fetchMeterDetail,
  fetchZQFXData,
  fetchQSFXData,
  fetchEBarData,
  fetchRYQGLData,
  saveParamsByMeterId,
  fetchZZQQS,
  fetchQNYQFX
} from '@/api/gasLawTablesDay'

const defaultState = () => {
  return {
    defaultDate: undefined,
    tableData: null,
    tableLoading: false,
    tableHint: '',
    tablePageParams: {
      pageNum: 1,
      pageSize: 20
    },
    userQueryParams: {
      unitId: undefined,
      unitName: undefined
    },
    stopTableKeyUp: false,
    treeMapList: null,
    centerTopChartLoading: false,
    centerBottomChartLoading: false,
    centerTopCandList: [],
    currentMeterId: undefined,
    currentGasCls: undefined,
    collapseLeftFlag: false,
    collapseRightFlag: false,
    bottomBarList: [],
    meterDetail: null,
    selecteType: undefined,
    zqfxList: [],
    qsfxList: [],
    startTime: undefined,
    endTime: undefined,
    selecteYear: undefined,
    RYQGLList: [],
    candleZoomStart: 0,
    candleZoomEnd: 0,
    ZZQQSList: [],
    ZZQQSLoading: false,
    ZZQQSSelectedPoint: [],
    ZQMSList: [],
    QNYQFXList: []
  }
}

function getStartAndEndTime(allList = [], candleZoomStart = 0, candleZoomEnd = 0) {
  let _startTime
  let _endTime
  const _len = allList.length
  const _start = round((candleZoomStart / 100) * _len)
  const _end = round((candleZoomEnd / 100) * _len) + 1
  const _candList = slice(allList, _start, _end)
  if (_candList.length > 0) {
    const _fList = head(_candList)
    const _eList = last(_candList)
    if (isArray(_fList) && _fList[0]) {
      _startTime = _fList[0]
    }
    if (isArray(_eList) && _eList[0]) {
      _endTime = _eList[0]
    }
  }
  return {
    startTime: _startTime,
    endTime: _endTime
  }
}

export default {
  namespaced: true,
  name: 'tablesDay',
  state: defaultState(),
  getters: {
    getTablePageParams: state => {
      return {
        ...state.tablePageParams
      }
    }
  },
  mutations: {
    /**
     * desc: 设置表格数据
     * param {type}
     * return {type} void
     */
    SET_TABLE_DATA(state, tableData) {
      state.tableData = tableData
    },
    /**
     * desc: 设置表格加载状态
     * param {type}
     * return {type} void
     */
    SET_TABLE_LOADING(state, flag) {
      state.tableLoading = flag
    },
    /**
     * desc: 设置表格请求页数
     * param {type}
     * return {type} void
     */
    SET_TABLE_PAGE_NUM(state, num) {
      state.tablePageParams.pageNum = num
    },
    /**
     * desc: 设置表格键盘操作标识符
     * param {type}
     * return {type} void
     */
    SET_STOP_TABLE_KEYUP(state, flag) {
      state.stopTableKeyUp = flag
    },
    /**
     * desc: 设置矩形树图数据
     * param {type}
     * return {type} void
     */
    SET_TREEMAP_DATA(state, data) {
      state.treeMapList = data
    },
    SET_CURRENT_METERID(state, meterId) {
      state.currentMeterId = meterId
    },
    SET_COLLAPSE(state, { type, status }) {
      if (type === 'left') {
        state.collapseLeftFlag = status
      } else if (type === 'right') {
        state.collapseRightFlag = status
      }
    },
    SET_CENTER_TOP_CANDDATA(state, data) {
      state.centerTopCandList = data
    },
    SET_METER_DETAIL(state, data) {
      state.meterDetail = data
    },
    SET_SELECT_TYPE(state, type) {
      state.selecteType = type
    },
    SET_ZQFX_DATA(state, data) {
      state.zqfxList = data
    },
    SET_QSFX_DATA(state, data) {
      state.qsfxList = data
    },
    SET_CENTER_TOP_CHART_LOADING(state, flag) {
      state.centerTopChartLoading = flag
    },
    SET_CENTER_BOTTOM_CHART_LOADING(state, flag) {
      state.centerBottomChartLoading = flag
    },
    SET_BOTTOM_BAR_DATA(state, data) {
      state.bottomBarList = data
    },
    REST_STATE(state) {
      state = assign(state, defaultState())
    },
    SET_DEFAULT_DATE(state, date) {
      state.defaultDate = date
    },
    SET_START_AND_END_TIME(state, dates) {
      const [startTime, endTime] = dates
      state.startTime = startTime || undefined
      state.endTime = endTime || undefined
    },
    SET_RYQGL_DATA(state, data) {
      state.RYQGLList = data
    },
    SET_CANDLE_ZOOM_RANG(state, data = {}) {
      const { start, end } = data
      state.candleZoomStart = start
      state.candleZoomEnd = end
    },
    SET_ZZQQS_DATA(state, list) {
      state.ZZQQSList = list
    },
    SET_ZZQQS_LOADING(state, flag) {
      state.ZZQQSLoading = flag
    },
    SET_ZZQQS_SELECTED_POINT(state, list) {
      state.ZZQQSSelectedPoint = list
    },
    SET_ZQMS_LIST(state, list) {
      state.ZQMSList = list
    },
    SET_QNYQFX_LIST(state, list) {
      state.QNYQFXList = list
    },
    SET_SELECTE_YEAR(state, year) {
      state.year = year
    },
    SET_CURRENT_GAS_CLs(state, type) {
      state.currentGasCls = type
    },
    SET_USER_QUERY_PARAMS(state, data) {
      state.userQueryParams = {
        ...state.userQueryParams,
        ...data
      }
    }
  },
  actions: {
    /**
     * desc: 获取表格数据
     * param {type}
     * return {type} void
     */
    async loadTableData(ctx, params) {
      ctx.commit('SET_TABLE_LOADING', true)
      const _tableData = await fetchTableData({
        ...ctx.state.tablePageParams,
        ...params
      })
      ctx.commit('SET_TABLE_LOADING', false)
      const { code, date = {} } = _tableData
      if (code === 200) {
        ctx.commit('SET_TABLE_DATA', date)
      }
    },
    /**
     * desc: 修改表格页码
     * param {type}
     * return {type} void
     */
    changeTablePageNum(ctx, num) {
      ctx.commit('SET_TABLE_PAGE_NUM', num)
    },
    /**
     * desc: 是否允许表格键盘操作
     * param {type}
     * return {type} void
     */
    changeStopTableKeyUp(ctx, flag) {
      ctx.commit('SET_STOP_TABLE_KEYUP', flag)
    },
    /**
     * desc: 获取矩形树图
     * param {type}
     * return {type} void
     */
    async loadTreeMapData(ctx) {
      const { code, date } = await fetchTreeMap()
      if (code === 200) {
        ctx.commit('SET_TREEMAP_DATA', date)
      }
    },
    changeCurrentMeterId(ctx, meterId) {
      ctx.commit('SET_CURRENT_METERID', meterId)
    },
    changeCollapse(ctx, arg) {
      ctx.commit('SET_COLLAPSE', arg)
    },
    async loadCenterTopCandData(ctx, params = {}) {
      ctx.commit('SET_CENTER_TOP_CHART_LOADING', true)
      const { code, date } = await fetchCenterTopCandData({
        ...params,
        meterId: ctx.state.currentMeterId
      })
      if (date.length > 0) {
        const _oldDate = head(date) ? head(date)[0] : undefined
        const _newDate =
          _oldDate &&
          dayjs(_oldDate)
            .subtract(1, 'days')
            .format('YYYY-MM-DD')
        ctx.commit('SET_DEFAULT_DATE', _newDate)
      }
      ctx.commit('SET_CENTER_TOP_CHART_LOADING', false)
      if (code === 200) {
        if (date.length > 0) {
          const _list = [...date, ...ctx.state.centerTopCandList]
          ctx.commit('SET_CENTER_TOP_CANDDATA', _list)
          if (ctx.state.selecteType) {
            ctx.dispatch('loadDataBySelectType')
          }
        } else {
          Message.warning('没有可加载的数据了')
        }
      }
    },
    async lodaMeterDetail(ctx) {
      const { code, date } = await fetchMeterDetail(ctx.state.currentMeterId)
      if (code === 200) {
        ctx.commit('SET_METER_DETAIL', date)
      }
    },
    changeSelectType(ctx, type) {
      ctx.commit('SET_SELECT_TYPE', type)
    },
    loadDataBySelectType(ctx, params) {
      ctx.dispatch('clearRYQGLList')
      const { selecteType: type, centerTopCandList: allList, candleZoomStart, candleZoomEnd } = ctx.state
      const { startTime, endTime } = getStartAndEndTime(allList, candleZoomStart, candleZoomEnd)
      const _pars = {
        ...params,
        startTime,
        endTime
      }
      switch (type) {
        case 'ryqtj':
          ctx.dispatch('loadEBarData', _pars)
          break
        case 'zqfx':
          ctx.dispatch('loadZQFXData', _pars)
          break
        case 'qnyqfx':
          ctx.dispatch('loadQNYQFXData', params)
          break
        default:
          break
      }
    },
    async loadZQFXData(ctx, params) {
      ctx.commit('SET_ZZQQS_DATA', [])
      ctx.commit('SET_ZZQQS_SELECTED_POINT', [])
      ctx.commit('SET_CENTER_BOTTOM_CHART_LOADING', true)
      const { code, date } = await fetchZQFXData({
        meterId: ctx.state.currentMeterId,
        ...params
      })
      ctx.commit('SET_CENTER_BOTTOM_CHART_LOADING', false)
      if (code === 200) {
        ctx.commit('SET_ZQFX_DATA', date)
      }
    },
    async loadQSFXData(ctx, params) {
      ctx.commit('SET_CENTER_BOTTOM_CHART_LOADING', true)
      const { code, date } = await fetchQSFXData({
        meterId: ctx.state.currentMeterId,
        ...params
      })
      ctx.commit('SET_CENTER_BOTTOM_CHART_LOADING', false)
      if (code === 200) {
        ctx.commit('SET_QSFX_DATA', date)
      }
    },
    async loadEBarData(ctx, params) {
      ctx.commit('SET_CENTER_BOTTOM_CHART_LOADING', true)
      const { code, date } = await fetchEBarData({
        ...params,
        meterId: ctx.state.currentMeterId
      })
      ctx.commit('SET_CENTER_BOTTOM_CHART_LOADING', false)
      if (code === 200) {
        ctx.commit('SET_BOTTOM_BAR_DATA', date)
      }
    },
    changeDefaultDate(ctx, date) {
      ctx.commit('SET_DEFAULT_DATE', date)
    },
    changeStartAndEndTime(ctx, dates) {
      ctx.commit('SET_START_AND_END_TIME', dates)
    },
    async loadRYQGLData(ctx, params) {
      const { code, date } = await fetchRYQGLData({
        ...params,
        meterId: ctx.state.currentMeterId,
        startTime: ctx.state.startTime,
        endTime: ctx.state.endTime
      })
      if (code === 200) {
        const { min, max } = params
        const _data = {
          ...date,
          min,
          max
        }
        const _list = [...ctx.state.RYQGLList, _data]
        ctx.commit('SET_RYQGL_DATA', _list)
      }
    },
    changeRYQGLList(ctx, index) {
      const _newList = cloneDeep(ctx.state.RYQGLList)
      _newList.splice(index, 1)
      ctx.commit('SET_RYQGL_DATA', _newList)
    },
    async loadSaveParams(ctx, data) {
      const _data = await saveParamsByMeterId({
        ...data,
        meterId: ctx.state.currentMeterId
      })
      return _data
    },
    clearCenterTopCandData(ctx) {
      ctx.commit('SET_CENTER_TOP_CANDDATA', [])
    },
    clearRYQGLList(ctx) {
      ctx.commit('SET_RYQGL_DATA', [])
    },
    clearStore(ctx) {
      ctx.commit('REST_STATE')
    },
    changeCandlZoomRange(ctx, data) {
      ctx.commit('SET_CANDLE_ZOOM_RANG', data)
    },
    async loadZZQQSData(ctx, params) {
      ctx.commit('SET_ZZQQS_LOADING', true)
      const { currentMeterId, centerTopCandList: allList, candleZoomStart, candleZoomEnd } = ctx.state
      const { startTime, endTime } = getStartAndEndTime(allList, candleZoomStart, candleZoomEnd)
      const _pars = {
        ...params,
        startTime,
        endTime
      }
      const { code, date } = await fetchZZQQS({
        meterId: currentMeterId,
        ..._pars
      })
      ctx.commit('SET_ZZQQS_LOADING', false)
      if (code === 200) {
        ctx.commit('SET_ZZQQS_DATA', [...ctx.state.ZZQQSList, date])
      }
    },
    changeZZQQSSelecetedPoint(ctx, point) {
      ctx.commit('SET_ZZQQS_SELECTED_POINT', [...ctx.state.ZZQQSSelectedPoint, point])
    },
    modifyZZQQSList(ctx, index) {
      const _oldList = cloneDeep(ctx.state.ZZQQSList)
      const _oldPointList = cloneDeep(ctx.state.ZZQQSSelectedPoint)
      _oldList.splice(index, 1)
      _oldPointList.splice(index, 1)
      ctx.commit('SET_ZZQQS_DATA', _oldList)
      ctx.commit('SET_ZZQQS_SELECTED_POINT', _oldPointList)
    },
    addZQMSList(ctx, list) {
      ctx.commit('SET_ZQMS_LIST', [...ctx.state.ZQMSList, list])
    },
    removeZQMSList(ctx, list) {
      const _newList = filter(ctx.state.ZQMSList, (item, index) => {
        const { value } = item
        if (!isEqual(value, list)) {
          return item
        }
      })

      ctx.commit('SET_ZQMS_LIST', _newList)
    },
    async loadQNYQFXData(ctx, params) {
      ctx.commit('SET_CENTER_TOP_CHART_LOADING', true)
      const {
        code,
        date: { list }
      } = await fetchQNYQFX({
        meterId: ctx.state.currentMeterId,
        year: ctx.state.year || undefined,
        ...params
      })
      ctx.commit('SET_CENTER_TOP_CHART_LOADING', false)
      if (code === 200) {
        ctx.commit('SET_QNYQFX_LIST', list)
      }
    },
    changeSelecteYear(ctx, year) {
      ctx.commit('SET_SELECTE_YEAR', year)
    },
    changeCurrentGasCls(ctx, type) {
      ctx.commit('SET_CURRENT_GAS_CLs', type)
    },
    changeUserQueryParams(ctx, data) {
      ctx.commit('SET_USER_QUERY_PARAMS', data)
    }
  }
}
